package lol.clann.minecraft.springboot.plugin.bukkit.impl;

import lol.clann.minecraft.springboot.api.annotation.compatibility.CompatibilityChecked;
import lol.clann.minecraft.springboot.api.bukkit.utils.ChatSerializerUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.LocationUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.PacketUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.WorldUtils;
import lol.clann.minecraft.springboot.bukkit.utils.BukkitUtils;
import net.minecraft.server.v1_7_R4.ChatComponentText;
import net.minecraft.server.v1_7_R4.PacketPlayOutBlockChange;
import net.minecraft.server.v1_7_R4.PacketPlayOutChat;
import net.minecraft.server.v1_7_R4.PacketPlayOutHeldItemSlot;
import org.bukkit.World;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author pyz
 * @date 2019/5/2 5:48 PM
 */
@Service
@CompatibilityChecked
public class PacketUtilsImpl_all implements PacketUtils {
    @Autowired
    private WorldUtils worldUtils;
    @Autowired
    private LocationUtils locationUtils;
    @Autowired
    private ChatSerializerUtils chatSerializerUtils;
    
    @Override
    public <T> T newPacketPlayOutBlockChange(int x, int y, int z, World world) {
        if (BukkitUtils.getBukkitVersionNumber() < 10800) {
            return (T) new PacketPlayOutBlockChange(x, y, z, worldUtils.toNMS(world));
        } else {
            return (T) new net.minecraft.server.v1_8_R3.PacketPlayOutBlockChange(worldUtils.toNMS(world), locationUtils.newBlockPosition(x, y, z));
        }
    }

    @Override
    public <T> T newPacketPlayOutHeldItemSlot(int hotbar) {
        return (T) new PacketPlayOutHeldItemSlot(hotbar);
    }

    @Override
    public <T> T newPacketPlayOutChat(String message) {
        return (T) new PacketPlayOutChat(fromJson(message));
    }

    protected <T> T fromJson(String json) {
        if (!json.trim().startsWith("{")) {
            return (T) new ChatComponentText(json);
        } else {
            return (T) chatSerializerUtils.deserialize(json);
        }
    }

}
